extends Node2D
class_name DesignGrid

@export var cell_size : Vector2 = Vector2(128,128)
const BASE_CELL_PRE = preload("res://grid/base_cell.tscn")
const SPACE : Vector2 = Vector2(4.0,4.0)
var grid_xy : Vector2i = Vector2i.ZERO
var grid_data : Dictionary
var cells : Dictionary
var is_need_back : bool
var sp_set_current_type = {
	"in" : [4,5,6,7]
}

func _ready() -> void:
	_init_pos()
	_init_grid()

func _init_pos() -> void :
	var base_cell = BASE_CELL_PRE.instantiate()
	base_cell.item_size = cell_size
	global_position.x -= ((grid_xy.x - 1) * cell_size.x + SPACE.x * (grid_xy.x - 1))/ 2.0
	global_position.y -= ((grid_xy.y - 1) * cell_size.y + SPACE.y * (grid_xy.y - 1))/ 2.0

func _init_grid() :
	for y in grid_xy.y :
		for x in grid_xy.x :
			var cell = BASE_CELL_PRE.instantiate()
			cell.item_size = cell_size
			cell._save_xy(x,y)
			cell.is_debug = true
			cell.on_click_event.connect(_cell_click)
			cell.type = cells.get(Vector2i(x,y),-1)
			_add_cell(cell,x,y)

func _add_cell(base_cell,x=0,y=0) -> void :
	base_cell.position = Vector2(x * base_cell.item_size.x,y * base_cell.item_size.y) + Vector2(SPACE.x * x,SPACE.y * y)
	add_child(base_cell)

func _cell_click(cell) -> void :
	var new_type = get_parent().current_type
	if sp_set_current_type.in.has(new_type) :
		_reset_target_cell_type(new_type)
	cell.type = new_type

func _get_grid_data() -> Dictionary :
	var childs = get_children()
	var result = {
		"grid_xy" : grid_xy,
		"is_need_back" : is_need_back,
		"cells" : {}
	}
	for child in childs :
		if is_same(child.type,GlobelEnum.CellType.Block) : continue
		result.cells[child.xy] = child.type
	return result

func _reset_target_cell_type(type : GlobelEnum.CellType) -> void :
	var childs = get_children()
	for child in childs :
		if is_same(child.type,type) :
			child.type = GlobelEnum.CellType.Block
